package com.example.SocketSelectorStudy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 接收客户端的数据,加密后返回数据给客户端
 */
public class MySelectorServer {

    public static void main(String[] args) {
        try {
            run(8888);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    public static ByteBuffer sendBuffer = ByteBuffer.allocate(1024);

    private static void run(int listenPort) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(listenPort));

        Selector selector = Selector.open();
        //false表示非阻塞模式,true表示阻塞模式
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            //选择器在这里阻塞
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
                    //连接到client的管道
                    SocketChannel client = server.accept();
                    System.out.println("accept one client, ready to read.");
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    readBuffer.clear();
                    client.read(readBuffer);
                    String readString = new String (readBuffer.array());
                    System.out.println("客户端"+Thread.currentThread().getId()+":"+readString);
                    //加密
                    String encryption = encryptReadString(readString);
                    sendBuffer.flip();
                    sendBuffer = ByteBuffer.wrap(encryption.getBytes());
                    client.write(sendBuffer);
                    System.out.println("响应客户端"+Thread.currentThread().getId()+":"+encryption);
                }
                iterator.remove();
            }

        }


    }

    private static String encryptReadString(String readString) {
        return "模拟加密"+readString.trim();
    }


}
